<?php

namespace app\controller;

use app\BaseController;
use app\model\OrderModel;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\middleware\Check;
use think\validate\ValidateRule;

require_once '../sdk/WxpayAPI/lib/WxSend.Api.php';
require_once '../sdk/API-PHP/API_PHP_DEMO.php';

/**
 * Class Order 骑手端控制器
 * @package app\controller
 */
class Rider extends BaseController
{
    protected $middleware = [Check::class];

    /** 获取所有订单
     * @param Request $request
     */
    public function order_list(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $status = $this->request->param('status');//状态
        if (is_null($status)) return jsonFail('缺少参数');
        if (empty($user_id)) return jsonFail('缺少用户ID');
        $user = Db::table('eb_user')->where('id', $user_id)->find();
        $delivery_storieds = explode(',', $user['delivery_storied']);
        if ($user['delivery_type'] == 1) {//暂停接单
            return jsonSuccess('获取成功', []);
        }

        $data = Db::table('eb_order')->alias('a')
            ->leftJoin('eb_user w', 'a.user_id = w.id')
            ->leftJoin('eb_store u', 'a.store_id = u.id')
            ->leftJoin('eb_school b', 'a.school_id = b.id')
            ->leftJoin('eb_dormitory c', 'a.dormitory_id = c.id')
            ->order('a.create_time', 'desc')
            ->where('a.status', $status)
            ->where('a.is_pay', 1)
            ->where('w.school_id', $user['school_id'])
            ->where('a.dormitory_id', 'in', $delivery_storieds)
            ->field('a.is_overtime,u.bank_phone,c.name as dormitory_name,b.name as school_name,a.*,u.shop_name,u.address,u.logo')
            ->select()->toArray();
//        $order_Ids = array_column($data, 'id');
//        $storeIds = array_column($data, 'store_id');
//        $order_dedil = Db::table('eb_order_detail')->where('order_id','in',$order_Ids)->select()->toArray();
//        $goods_Ids = array_column($order_dedil, 'goods_id');
//        $goods = Db::table('eb_goods')->where('store_id','in',$storeIds)->where('id','in',$goods_Ids)->select()->toArray();

        foreach ($data as $key => &$value) {
            $value['order_detail'] = Db::table('eb_order_detail')->where('order_id', $value['id'])->select()->toArray();
            foreach ($value['order_detail'] as $key1 => &$value1) {
                $value1['goods'] = Db::table('eb_goods')->where('id', $value1['goods_id'])->find();
            }
        }
        return jsonSuccess('获取成功', $data);
    }

    /** 抢单
     * @param Request $request
     */
    public function rob_order(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $order_no = $this->request->param('order_no');//订单号ID
        $order = Db::table('eb_order')->where('order_no', $order_no)->find();
        $user_info = Db::table('eb_user')->where('id', $user_id)->find();
        try {
            Db::startTrans();
            $send = new \WxSendApi();
            $res = Db::table('eb_order')->where('order_no', $order_no)->where('status', 1)->update(['status' => 2, 'send_id' => $user_id, 'receipt_time' => time()]);
            if ($res != 0) {
                $ds = json_decode($send->send_Template_dynamic($order['user_id'], $user_id, $order), true); //转为数组;
            }
            if ($user_info['type'] == 3) {//专业骑手
                $redis = new \Redis();
                $redis->connect('127.0.0.1');
                $redis->zIncrBy('operate-' . $order['operate_id'], 1, $user_id);
            }
            if ($res != 0 && $ds['errcode'] == 0) {
                Db::commit();
                return jsonSuccess('抢单成功');
            } else {
                Db::rollback();
                return jsonFail('抢单失败，改单已被别人抢');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }
    }

    /** 配送员送货
     * @param Request $request
     */
    public function delivery_order(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单号ID
        $res = Db::table('eb_order')->where('order_no', $order_no)->update(['status' => 3, 'send_time' => time()]);
        if ($res != 0) return jsonSuccess('修改成功');
        return jsonFail('修改失败');
    }

    /** 确认送达
     * @param Request $request
     */
    public function arrive_order(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $order_no = $this->request->param('order_no');//订单号ID
        $order = Db::table('eb_order')->where('order_no', $order_no)->find();
        $config = Db::table('eb_admin')->where('id', $order['operate_id'])->find();
        $user_info = Db::table('eb_user')->where('id', $order['send_id'])->find();
        $time = time();
        $arive = $config['delivery_time'] * 60;
        $over_time = ($time - $order['send_time']) / 60;
        try {
            Db::startTrans();
            if ($time - $order['send_time'] > $arive) {
                $is_overtime = 1;//已超时
                $res = Db::table('eb_order')->where('order_no', $order_no)->update(['status' => 4, 'arrive_time' => $time, 'is_overtime' => $is_overtime, 'over_time' => ceil($over_time)]);
            } else {
                $is_overtime = 0;//未超时
                $res = Db::table('eb_order')->where('order_no', $order_no)->update(['status' => 4, 'arrive_time' => $time, 'is_overtime' => $is_overtime]);
            }
            $send = new \WxSendApi();
            $ds = json_decode($send->send_Template_arrive($order['user_id'], $order), true); //转为数组;
            if ($user_info['type'] == 3) {//专业骑手
                $redis = new \Redis();
                $redis->connect('127.0.0.1');
                $redis->zIncrBy('operate-' . $order['operate_id'], -1, $order['send_id']);
            }
            if ($res != 0 && $ds['errcode'] == 0) {
                Db::commit();
                return jsonSuccess('修改成功');
            } else {
                Db::rollback();
                return jsonFail('修改失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return jsonFail($e->getMessage());
        }

    }

    /** 骑手每日流水
     * @param Request $request
     */
    public function report(Request $request)
    {
        if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
        $user_id = $this->request->param('user_id');//用户ID
        $time = $this->request->param('time');//time
        if (empty($time)) return jsonFail('缺少参数');
        $data['list'] = Db::table('eb_order')->where('send_id', $user_id)->where('status', '>=', 4)->whereDay('create_time', $time)->select()->toArray();
        $data['History_money'] = Db::table('eb_order')->where('send_id', $user_id)->where('status', '>=', 5)->sum('delivery_price');
        $data['History_num'] = Db::table('eb_order')->where('send_id', $user_id)->where('status', '>=', 5)->count();
        return jsonSuccess('获取成功', $data);
    }

    public function test(Request $request)
    {
        $order_no = $this->request->param('order_no');//用户ID
        $send = new \API_PHP_DEMO();
        var_dump(123);
        exit;
//        $printerContent = "921527944#jqwgmaq9#测试打印机";
        $arr[0] = array('title' => '酸菜鱼', 'price' => '100.4', 'num' => '10');
        $arr[1] = array('title' => '可乐鸡翅+蒜蓉蒸扇贝', 'price' => '10.3', 'num' => '6');
        $arr[2] = array('title' => '紫苏焖鹅+梅菜肉饼+椒盐虾+北京烤鸭', 'price' => '10.0', 'num' => '8');
//        $data = Db::table('eb_order')->where('order_no',$order_no)->find();
//        $store = Db::table('eb_store')->where('id',$data['store_id'])->find();
//        $user = Db::table('eb_user')->alias('a')
//            ->leftJoin('eb_school b', 'a.school_id = b.id')
//            ->leftJoin('eb_dormitory c', 'a.dormitory_id = c.id')
//            ->field('a.address,a.phone,b.name as school_name,c.name as dormitory_name')
//            ->where('a.id',$data['user_id'])->find();
//        $order = Db::table('eb_order_detail')
//            ->alias('a')
//            ->leftJoin('eb_goods b', 'a.goods_id = b.id')
//            ->where('a.order_id', $data['id'])
//            ->field('a.*,b.*')
//            ->select()->toArray();
//        echo"<pre>";
//        var_dump($order);exit;
//        $data = combination($store,$user,$data,$order,14,6,3,6);
        $printerContent = "921527944";
        $res = $send->printMsg();
        var_dump(json_decode($res, true));
    }
}
